package com.me.chat.util;


import com.me.chat.pojo.suport.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.exceptions.InvalidTokenException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * @Authhor: qiu
 * @Date: 2021/11/13 4:46 下午
 */

/**
 * 简单的用户信息
 */
@Component
public class SimpleUserInfo {

    @Autowired
    TokenStore tokenStore;

    /**
     * 获取用户对象
     * @return
     */
    private static User simpleInfo() {
        User principal = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return principal;
    }

    /**
     * 获取用户id 但是只适用于有/res/下的接口 以及单机环境 因为该用户信息是存在本地的
     * @return
     */
    public static String getUserId() {
        User principal =  simpleInfo();
        String userId = principal.getId();
        return userId;
    }

    /**
     * 根据token 解析出用户信息
     */
    public String getUserId(String token) {
        // 校验token是否已经过期或者失效
        OAuth2AccessToken accessToken = tokenStore.readAccessToken(token);

        if (accessToken == null) {
            throw new InvalidTokenException("Invalid access token: " + token);
        }
        else if (accessToken.isExpired()) {
            tokenStore.removeAccessToken(accessToken);
            throw new InvalidTokenException("Access token expired: " + token);
        }

        OAuth2Authentication oAuth2Authentication = tokenStore.readAuthentication(token);
        //获得用户信息
        User principal = (User)oAuth2Authentication.getPrincipal();
        String userId = principal.getId();

        return userId;
    }

    /**
     * 根据请求体中的token来获得用户信息
     * @param request
     * @return
     */
    public String getUserId(HttpServletRequest request) {

        //解析token 去掉bearer
        String token = getTokenFromHeader(request);

        String userId = this.getUserId(token);

        return userId;
    }

    /**
     * 获取请求头中中token
     * @param request
     * @return
     */
    public static String getTokenFromHeader(HttpServletRequest request) {
        //从请求头中获取token
        String tokenAll = request.getHeader("Authorization").trim();
        //不区分大小写替换bearer 以及 空格
        String token = tokenAll.replaceFirst("(?i)bearer","")
                .replace(" ","");

        return token;
    }
}
